<template>
  <div class="app-container">
    <!-- 添加/修改按钮 -->
    <el-button type="primary" icon="el-icon-plus" @click="addTradeMark">添加</el-button>
    <!-- 表格 -->
    <el-table style="margin: 20px 0" border :data="list">
      <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="tmName" label="品牌名称"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template slot-scope="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作">
        <template slot-scope="{ row, $index }">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="editTradeMark(row)">
            修改
          </el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteTradeMark(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 
      分页器 
      -> 符号让右侧的sizes, total属性都去最右侧
      page-count 显示的页码个数
    -->
    <el-pagination
      style="text-align: center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-count="7"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pageSize"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="totalCount"
    ></el-pagination>
    <!-- 添加对话框 -->
    <el-dialog
      :title="tmForm.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogFormVisible"
      width="700px"
    >
      <el-form ref="tmForm" :model="tmForm" :rules="rules">
        <el-form-item prop="tmName" label="品牌名称" :label-width="formLabelWidth">
          <el-input v-model="tmForm.tmName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="logoUrl" label="品牌logo" :label-width="formLabelWidth">
          <!-- 
            上传图片，这里不是表单元素不能使用v-model
            -> action: 图片上传的地址
            -> list-type: 文件列表的类型
            -> on-success: 上传成功的回调
            -> before-upload: 上传之前的回调
          -->
          <el-upload
            class="avatar-uploader"
            :action="baseApi + '/admin/product/fileUpload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TradeMark',
  components: {},
  data() {
    return {
      list: [],
      pageNum: 1,
      pageSize: 5,
      totalCount: 0,
      dialogFormVisible: false,
      formLabelWidth: '100px',
      baseApi: '',
      tmForm: {
        tmName: '',
        logoUrl: '',
      },
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' },
        ],
        logoUrl: [{ required: true, message: '请上传品牌图片' }],
      },
    };
  },
  mounted() {
    this.baseApi = process.env.VUE_APP_BASE_API;
    this.getTradeMarkList();
  },
  methods: {
    async getTradeMarkList(pager = 1) {
      this.pageNum = pager;
      const { pageNum, pageSize } = this;
      let result = await this.$API.trademark.reqTradeMarkList(pageNum, pageSize);
      console.log(result);
      if (result.code === 200) {
        this.list = result.data.records;
        this.totalCount = result.data.total;
      }
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getTradeMarkList();
    },
    handleCurrentChange(page) {
      this.pageNum = page;
      this.getTradeMarkList();
    },
    addTradeMark() {
      this.tmForm = {
        tmName: '',
        logoUrl: '',
      };
      this.dialogFormVisible = true;
    },
    editTradeMark(row) {
      this.dialogFormVisible = true;
      // 这里不能直接对row进行操作，否则会修改服务器返回所展示的数据
      this.tmForm = { ...row };
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      console.log(file);

      const isJPG = file.type === 'image/jpeg' || 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    async addOrUpdateTradeMark() {
      this.$refs.tmForm.validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          let result = await this.$API.trademark.reqAddOrUpdateTradeMark(this.tmForm);

          if (result.code === 200) {
            this.$message.success(this.tmForm.id ? '修改品牌成功' : '添加品牌成功');
            // 如果添加需要返回第一页，如果修改需要返回当前页
            this.getTradeMarkList(this.tmForm.id ? this.pageNum : 1);
          } else {
            this.$message.error(this.tmForm.id ? '修改品牌成功' : '添加品牌成功');
          }
        } else {
          // this.$message.error('表单验证失败');
        }
      });
    },
    deleteTradeMark(row) {
      this.$confirm(`你确定删除${row.tmName}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 点击确定会触发
          let result = await this.$API.trademark.reqDeleteTradeMark(row.id);
          if (result.code === 200) {
            this.$message.success('删除品牌成功');
            this.getTradeMarkList(this.list.length > 1 ? this.pageNum : 1);
          } else {
            this.$message.error('删除品牌失败');
          }
        })
        .catch(() => {
          // 点击取消会触发
          this.$message.info('已取消删除');
        });
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
